package com.likou.top100;

import java.util.HashMap;

public class Demo001_两数之和 {
    public static void main(String[] args) {
        int nums[] = {11,7,2,15};
        int target = 9;
        int[] ints = twoSum2(nums, target);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(nums[i]);
        }

    }

    /**
     * 时间复杂度O(n方)
     * @param nums 数组
     * @param target  目标值
     * @return  下标
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    /**
     * 时间复杂度O(n)
     * @param nums 数组
     * @param target  目标值
     * @return  下标
     */
    public static int[] twoSum2(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer,Integer> hm = new HashMap<>();
        for(int i = 0; i < nums.length ; i ++){
            if(hm.containsKey(nums[i])){
                result[0] = hm.get(nums[i]);
                result[1] = i;
                return result;
            }else{
                hm.put(target - nums[i],i);
            }
        }
        return null;
    }
}
